﻿using CodeSHARPer.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;

namespace CodeSHARPer.Services
{
    public class LastOpenedFilesManager : ViewModel.Base.ViewModelBase
    {
        #region Singleton
        private static volatile LastOpenedFilesManager instance;
        private static object syncRoot = new Object();

        #region constructor
        /// <summary>
        /// Constructor
        /// </summary>
        private LastOpenedFilesManager() { }
        #endregion constructor

        public static LastOpenedFilesManager Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new LastOpenedFilesManager();
                    }
                }

                return instance;
            }
        }
        #endregion Sigleton

        private ObservableCollection<OpenedFile> lastOpenedFiles;
        public ObservableCollection<OpenedFile> LastOpenedFiles
        {
            get
            {
                if (this.lastOpenedFiles == null)
                    this.lastOpenedFiles = new ObservableCollection<OpenedFile>();
                return this.lastOpenedFiles;
            }
            set
            {
                if (this.lastOpenedFiles != value)
                {
                    this.lastOpenedFiles = value;
                    this.NotifyPropertyChanged(Cinch.ObservableHelper.CreateArgs<LastOpenedFilesManager>(c => c.LastOpenedFiles));
                }
            }
        }

        public void AddFileToList(string fileName)
        {
            if (File.Exists(fileName))
            {
                //check for file in the list
                OpenedFile file = FindFileInList(fileName);

                if (file == null)
                    this.LastOpenedFiles.Add(new OpenedFile { PathFileName = fileName });
            }
        }

        public OpenedFile FindFileInList(string fileName)
        {
            return this.LastOpenedFiles.SingleOrDefault(f => f.PathFileName.Equals(fileName, StringComparison.OrdinalIgnoreCase));
        }

        public void RemoveFileInList(string fileName)
        {
            //check for file in the list
            OpenedFile file = FindFileInList(fileName);

            if (file != null)
                this.LastOpenedFiles.Remove(file);
        }

        public void RemoveFileInList(OpenedFile file)
        {
            if (file != null)
                this.LastOpenedFiles.Remove(file);
        }
    }
}
